import threading
import tkinter
from multiprocessing import Queue
from tkinter import ttk


class ProgressDialog:

    def __init__(self, parent_window: tkinter.Tk):
        self.dialog = None
        self.parent_window = parent_window
        self.progress_var: tkinter.IntVar = tkinter.IntVar()
        self.queue: Queue = Queue()

    def init_dialog(self, dialog):
        dialog_start_x = int(self.parent_window.winfo_x() + self.parent_window.winfo_reqwidth() / 2 - self.dialog.winfo_reqwidth() / 2)
        dialog_start_y = int(self.parent_window.winfo_y() + self.parent_window.winfo_reqheight() / 2 - self.dialog.winfo_reqheight() / 2)
        dialog.geometry(f"200x100+{dialog_start_x}+{dialog_start_y}")
        dialog.title("等待操作完成...")

        bar = ttk.Progressbar(dialog, maximum=100, length=200, mode="determinate", orient=tkinter.HORIZONTAL, variable=self.progress_var)
        bar.pack(fill=tkinter.X, pady=10, padx=10)
        bar.after(50, self.update_progress, bar)

    def fn_empty(self, *args, **kwargs):
        pass

    def update_progress(self, bar: ttk.Progressbar):
        if not self.queue.empty():
            val = self.queue.get(block=False)
            self.progress_var.set(val)
        bar.after(50, self.update_progress, bar)

    def show(self, call_back):
        self.parent_window.wm_attributes("-disabled", True)
        self.dialog = tkinter.Toplevel()
        self.dialog.protocol("WM_DELETE_WINDOW", func=self.fn_empty)

        self.init_dialog(self.dialog)
        self.dialog.transient(self.parent_window)
        t = threading.Thread(target=self.close, kwargs={
            "call_back": call_back
        })
        t.setDaemon(True)
        t.start()

    def close(self, call_back):
        call_back(self.queue)
        self.parent_window.wm_attributes("-disabled", False)
        self.dialog.destroy()
        self.parent_window.deiconify()
